package common

import (
	"fmt"
	"os"
	"strconv"
	"io/ioutil"
	"log"
)

type BuildPath string

func (bpath BuildPath) CreateNextBuildDir() (maxDirNum string,err error) {
	fs, err := ioutil.ReadDir(string(bpath))
	if err != nil {
		log.Println(err)
		return
	}
	if len(fs) == 0 {
		maxDirNum = "1"
		nextBuildNum := string(bpath) + "/" + maxDirNum
		err = os.Mkdir(nextBuildNum, os.ModePerm)
		if err != nil {
			log.Println("mkdir build err " , err.Error())
			return
		}
	} else {
		var dirs []string
		for _,f := range fs {
			if f.IsDir() {
				dirs = append(dirs,f.Name())
			}
		}
		maxDirNum = strconv.Itoa( getMaxDir(dirs) + 1)
		nextBuildNum := string(bpath) + "/" + string(maxDirNum)
		fmt.Println("next build dir " , nextBuildNum)
		err = os.Mkdir(nextBuildNum, os.ModePerm)
		if err != nil {
			log.Println("mkdir builds dir error :" , err.Error())
			return
		}
	}
	return
}

func getMaxDir(dirs []string)(int)  {
	flag,maxDir := 0 , 0
	//maxDir,err := strconv.Atoi(dirs[0])
	for i:= 0 ; i < len(dirs) ; i++ {
		num,err := strconv.Atoi(dirs[i])
		if err == nil {
			flag = i
			maxDir = num
			break
		}
	}
	for i:=flag; i<len(dirs);i++ {
		num,err := strconv.Atoi(dirs[i])
		if err != nil {
			continue
		} else {
			if maxDir < num {
				maxDir = num
			}
		}
	}
	return maxDir
}
